import React, {Component} from 'react';
import {Image, StyleSheet, Text, TextInput, TouchableOpacity, View, Alert, AsyncStorage} from 'react-native';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import ImagePicker from 'react-native-image-crop-picker';
import Toast from '@remobile/react-native-toast';
import CountEmitter from './../../utils/event/CountEmitter';
import ModalDropdown from 'react-native-modal-dropdown';
import FetchUtils from './../../utils/FetchUtils';
import utils from './../../utils/utils';
import Spinner from "react-native-loading-spinner-overlay";

let imgs = [];
export default class MyEditPic extends Component {
    static navigationOptions = ({navigation, screenProps}) => ({
        headerTitle: "更新照片和尺寸",
        headerStyle: {
            backgroundColor: '#F6F6F6',
        },
        headerTitleStyle: {
            alignSelf: 'center',
            fontSize: utils.setSpText(17),
        },
        headerRight: <TouchableOpacity/>
    });

    constructor(props) {
        super(props);
        this.headerImg = '';
        this.selfImg = [];
        this.lapSize = '';
        this.pantsSize = '';
        this.shoesSize = '';
        this.state = {
            loadingStatus: false,
            registerButStatus: false,
            headerUrl: null,
            selfImg: [],
        }
    }

    render() {

        return (
            <View style={styles.pageView}>
                <Spinner visible={this.state.loadingStatus} textContent={"正在上传。。。"} textStyle={{color: '#000'}}/>

                <KeyboardAwareScrollView >
                    <View style={styles.pageOneView}>

                        <View style={styles.infoView}>
                            <View style={[styles.textInputPic, {
                                flexDirection: 'row',
                                justifyContent: 'space-between',
                                height: utils.autoheight(80),
                                borderBottomWidth: utils.autoheight(0.5)
                            }]}>
                                <Text style={styles.headerText}>头像</Text>
                                <TouchableOpacity style={styles.headerItemView} onPress={() =>
                                    ImagePicker.openPicker({
                                        cropping: false
                                    }).then(image => {
                                        this._singlePicker(image.path);
                                    })
                                }>
                                    <Image style={styles.headerImg} source={{uri: this.state.headerUrl}}/>
                                    <Image style={styles.rightPointImg}
                                           source={require('./../../../img/rightpoint.png')}/>
                                </TouchableOpacity>
                            </View>

                            <View style={[styles.textInputPic, {
                                borderColor: '#A0A0A0',
                                borderBottomWidth: utils.autoWidth(0.5)
                            }]}>
                                <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                                    <View style={{justifyContent: 'center', height: utils.autoheight(44)}}>
                                        <Text style={styles.headerText}>个人照片</Text>
                                    </View>
                                    <TouchableOpacity style={styles.headerItemView} onPress={() =>
                                        ImagePicker.openPicker({
                                            multiple: true
                                        }).then(images => {
                                            this._multiplePicker(images);
                                        })
                                    }>
                                        <Text>上传</Text>
                                        <Image style={styles.rightPointImg}
                                               source={require('./../../../img/rightpoint.png')}/>
                                    </TouchableOpacity>
                                </View>
                                <View style={{
                                    flexDirection: 'row',
                                    justifyContent: 'space-around',
                                    flexWrap: 'wrap',
                                    marginBottom: utils.autoheight(12)
                                }}>
                                    {this.state.selfImg}
                                </View>

                            </View>

                            <View style={[styles.textInputForm, {justifyContent: 'center'}]}>
                                <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                                    <Text style={{marginLeft: utils.autoWidth(12)}}>上衣尺码选择</Text>
                                    <View style={{flexDirection: 'row'}}>
                                        <ModalDropdown
                                            style={{width: utils.autoWidth(100),}}
                                            textStyle={{
                                                fontSize: utils.setSpText(15),
                                                color: '#010101',
                                                alignSelf: 'flex-end',
                                                marginRight: utils.autoWidth(13),
                                            }}
                                            options={['165/80A', '170/84A', '175/88A', '180/92A', '185/96A', '190/10A']}
                                            defaultValue="请选择尺码"
                                            onSelect={(index, value) => {
                                                this.lapSize = value;
                                            }}
                                        >
                                        </ModalDropdown>
                                        <View style={styles.sexInputViewMDViewImgView}>
                                            <Image style={styles.rightPointImg}
                                                   source={require('./../../../img/rightpoint.png')}/>
                                        </View>
                                    </View>
                                </View>
                            </View>

                            <View style={[styles.textInputForm, {justifyContent: 'center'}]}>
                                <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                                    <Text style={{marginLeft: utils.autoWidth(12)}}>裤装尺码选择</Text>
                                    <View style={{flexDirection: 'row'}}>
                                        <ModalDropdown
                                            style={{width: utils.autoWidth(100),}}
                                            textStyle={{
                                                fontSize: utils.setSpText(15),
                                                color: '#010101',
                                                alignSelf: 'flex-end',
                                                marginRight: utils.autoWidth(13),
                                            }}
                                            options={['165/80A', '170/84A', '175/88A', '180/92A', '185/96A', '190/10A']}
                                            defaultValue="请选择尺码"
                                            onSelect={(index, value) => {
                                                this.pantsSize = value;
                                            }}
                                        >
                                        </ModalDropdown>
                                        <View style={styles.sexInputViewMDViewImgView}>
                                            <Image style={styles.rightPointImg}
                                                   source={require('./../../../img/rightpoint.png')}/>
                                        </View>
                                    </View>
                                </View>
                            </View>

                            <View style={[styles.textInputForm, {justifyContent: 'center'}]}>
                                <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                                    <Text style={{marginLeft: utils.autoWidth(12)}}>鞋子尺码选择</Text>
                                    <View style={{flexDirection: 'row'}}>
                                        <ModalDropdown
                                            style={{width: utils.autoWidth(100),}}
                                            textStyle={{
                                                fontSize: utils.setSpText(15),
                                                color: '#010101',
                                                alignSelf: 'flex-end',
                                                marginRight: utils.autoWidth(13),
                                            }}
                                            options={['22.5', '23', '23.5', '24', '24.5', '25', '25.5', '26', '26.5', '27', '27.5', '28']}
                                            defaultValue="请选择尺码"
                                            onSelect={(index, value) => {
                                                this.shoesSize = value;
                                            }}
                                        >
                                        </ModalDropdown>
                                        <View style={styles.sexInputViewMDViewImgView}>
                                            <Image style={styles.rightPointImg}
                                                   source={require('./../../../img/rightpoint.png')}/>
                                        </View>
                                    </View>
                                </View>
                            </View>
                        </View>
                    </View>
                </KeyboardAwareScrollView>

                <View style={styles.nextTouchView}>
                    <TouchableOpacity style={styles.nextTouch} onPress={() => this._butSubmit()}>
                        <View style={styles.nextTouchTextView}><Text style={styles.nextTouchText}>确认修改</Text>
                            <Text style={styles.nextTouchText}>CONFIRM</Text>
                        </View>
                    </TouchableOpacity>
                </View>

            </View>
        );
    }

    /*按钮提交*/
    _butSubmit = () => {
        let params = {
            headerImg: this.headerImg,
            selfImg: this.selfImg,
            lapSize: this.lapSize,
            pantsSize: this.pantsSize,
            shoesSize: this.shoesSize,
        };
        AsyncStorage.getItem("XToken").then((xToken) => {
            console.log(params);
            FetchUtils.postWithParamHeader(utils.apiUrl + '/user/updatepic', params, xToken, (res) => {
                if (res.code !== 200) {
                    Toast.showShortBottom("修改错误：" + res.apiData);
                    this.setState({
                        loadingStatus: false,
                    })
                } else {
                    Toast.showShortBottom("修改成功");
                    CountEmitter.emit("myRefresh");
                    this.props.navigation.goBack();
                }
            });
        });

    };

    /*上传单个头像*/
    _singlePicker(imgPath) {
        this.setState({
            loadingStatus: true,
        });
        FetchUtils.get(utils.apiUrl + '/qiniu/getToken', '', (res) => {
            console.log(res);
            let formData = new FormData();
            let file = {uri: imgPath, type: 'multipart/form-data'};
            formData.append("file", file);
            formData.append("token", res.apiData);
            FetchUtils.post("http://up-z2.qiniu.com/", formData, (res) => {
                console.log(res);
                this.headerImg = res.key;
                this.setState({
                    headerUrl: imgPath,
                    loadingStatus: false,
                });
            });
        });

    }

    /*上传多个个人照片*/
    _multiplePicker(imgPaths) {
        /*每次点击，清空数组*/
        this.state.selfImg.splice(0, imgs.length);
        this.selfImg.splice(0, this.selfImg.length);
        let selfImgView = [];
        this.setState({
            loadingStatus: true,
        });
        if (imgPaths.length > 20) {
            Alert.alert("警告", "个人照片最多上传20张")
        } else if (imgPaths.length > 0) {
            for (let n = 0; n < imgPaths.length; n++) {
                selfImgView.push(
                    <Image key={n} style={styles.selfImgStyle} source={{uri: imgPaths[n].path}}/>
                );
                FetchUtils.get(utils.apiUrl + '/qiniu/getToken', '', (res) => {
                    let formData = new FormData();
                    let file = {uri: imgPaths[n].path, type: 'multipart/form-data'}
                    formData.append("file", file);
                    formData.append("token", res.apiData);
                    FetchUtils.post("http://up-z2.qiniu.com/", formData, (res) => {
                        this.selfImg.push(res.key);
                    });
                });
            }
            this.setState({
                selfImg: selfImgView,
            })
        }

        setTimeout(() => {
            this.setState({
                loadingStatus: false,
            })
        }, 3000);
    }
}

const styles = StyleSheet.create({
    pageView: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-between',
        backgroundColor: '#FFFFFF',
    },
    pageOneView: {
        alignItems: 'center',
    },
    lineView: {
        flexDirection: 'row',
    },
    lineViewView: {
        flex: 1,
        flexDirection: 'row',
    },
    lineViewImg: {
        flex: 1,
        height: utils.autoheight(15),
    },
    textProfileView: {
        flexDirection: 'row',
        justifyContent: 'center',
    },
    textProfile: {
        fontSize: utils.setSpText(13),
        color: "#010101",
    },
    infoView: {
        marginTop: utils.autoheight(52),
    },
    textInputPic: {
        width: utils.autoWidth(320),
        borderColor: '#A0A0A0',
        borderTopWidth: utils.autoWidth(0.5),
        borderRightWidth: utils.autoWidth(0.5),
        borderLeftWidth: utils.autoWidth(0.5),
    },
    textInputForm: {
        width: utils.autoWidth(320),
        height: utils.autoheight(44),
        borderColor: '#A0A0A0',
        borderRightWidth: utils.autoWidth(0.5),
        borderLeftWidth: utils.autoWidth(0.5),
        borderBottomWidth: utils.autoWidth(0.5)
    },
    nextTouchView: {
        alignItems: 'center',
    },
    nextTouch: {
        width: utils.autoWidth(320),
        height: utils.autoheight(50),
        borderColor: '#010101',
        borderWidth: utils.autoWidth(2),
        alignItems: 'center',
        marginBottom: utils.autoheight(33),
    },
    nextTouchTextView: {
        alignItems: 'center',
    },
    nextTouchText: {
        fontSize: utils.setSpText(17),
        color: '#010101',
    },
    headerText: {
        alignSelf: 'center',
        marginLeft: utils.autoWidth(12),
    },
    headerItemView: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    headerImg: {
        height: utils.autoWidth(60),
        width: utils.autoWidth(60),
        borderRadius: utils.autoWidth(30),
    },
    rightPointImg: {
        width: utils.autoWidth(8),
        height: utils.autoheight(13),
        marginRight: utils.autoWidth(12),
        marginLeft: utils.autoWidth(6),
        alignSelf: 'center',
        justifyContent: 'center',
    },
    selfImgStyle: {
        width: utils.autoWidth(80),
        height: utils.autoWidth(80),
        borderRadius: utils.autoWidth(8),
        marginBottom: utils.autoheight(10),
    },
})